package com.health.viewscontrols;

import java.util.List;

import com.health.ConfigActivity;
import com.health.MainActivity_Menu_JTYS;
import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.db.DbManager;
import com.health.db.FDbManager;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_AREA;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.BD_ORGANIZE_INSTITUTION;
import com.health.tablebean.HD_PERSONAL_HEALTH_PHOTO;
import com.health.tablebean.JTYSCustomerDoctorCont;
import com.health.tablebean.SBCL_DATA;
import com.health.tools.GlobalConts;
import com.health.tools.SPUtil;
import com.nova.MainActivity;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.setting.PermissionSetting;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import static com.novabluetooth.services.ktxyj.Constants.AREA_CODE;

/**
 * 程序启动界面
 */

public class SplashActivity extends NovaActivity {
    private static final String TAG = "SplashActivity";
    private TextView tv_version;
    private String code = "4A5F634346A82B95";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        setContentView(R.layout.splash_ac);
        findViews();
        setListeners();

        // 方法1 Android获得屏幕的宽和高
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        @SuppressWarnings("deprecation")
        int screenWidth = display.getWidth();
        @SuppressWarnings("deprecation")
        int screenHeight = display.getHeight();
        Log.w(TAG, "" + screenWidth + "*" + screenHeight);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float width = dm.widthPixels * dm.density;
        float height = dm.heightPixels * dm.density;
        Log.w(TAG, "-----" + width + "*" + height);
        if (Build.VERSION.SDK_INT >= 23) {
            AndPermission.with(this).permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).onGranted(new Action() {
                @Override
                public void onAction(List<String> permissions) {
                    initApplicationData();
                    Handler x = new Handler();
                    x.postDelayed(new StartHandler(), 3000);
                }
            }).onDenied(new Action() {
                @Override
                public void onAction(List<String> permissions) {

                    Dialog dialog = new AlertDialog.Builder(SplashActivity.this).setTitle("重要提示！").setMessage("你已经拒绝了存储权限或蓝牙权限，请去设置界面开启权限，否则将影响使用！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            openSettingDetail();
                            //关闭app
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    }).show();

                }
            }).start();
        } else {
            initApplicationData();
            Handler x = new Handler();
            x.postDelayed(new StartHandler(), 3000);
        }


//		// 启动页面，延迟5秒钟，跳转登录页面
//		Handler x = new Handler();
//		x.postDelayed(new StartHandler(), 3000);
    }


    /**
     * 初始化数据
     */
    public void initApplicationData() {
        NovaApplication.fdbmanger = FDbManager.getInstance(SplashActivity.this);
        NovaApplication.dbManger = new DbManager(getApplicationContext());
        initCSDB();
        initDbData();
        insertAndUpdateData2BD_DDINFO();
    }

    /**
     * 数据库添加和修改字字典值    （门诊DM04-15_1  家庭DM04-15_2   电话DM04-15_3） DM04-04_2修改为家庭访视
     */
    private void insertAndUpdateData2BD_DDINFO() {
        List<BD_DD_INFO> infos = NovaApplication.fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
                "PARENTID = 'DM04-15'");
        if (infos != null && infos.size() > 0) {

        } else {
            BD_DD_INFO bd_dd_info1 = new BD_DD_INFO();
            bd_dd_info1.setDATAINFO("门诊");
            bd_dd_info1.setDATANUM("1");
            bd_dd_info1.setID("DM04-15_1");
            bd_dd_info1.setPARENTID("DM04-15");
            bd_dd_info1.setSORT("1");
            bd_dd_info1.setNBPHSC("Y");
            bd_dd_info1.setPrintNum("1");
            NovaApplication.fdbmanger.saveInInfoDB(bd_dd_info1);

            BD_DD_INFO bd_dd_info2 = new BD_DD_INFO();
            bd_dd_info2.setDATAINFO("家庭");
            bd_dd_info2.setDATANUM("2");
            bd_dd_info2.setID("DM04-15_2");
            bd_dd_info2.setPARENTID("DM04-15");
            bd_dd_info2.setSORT("2");
            bd_dd_info2.setNBPHSC("Y");
            bd_dd_info2.setPrintNum("2");
            NovaApplication.fdbmanger.saveInInfoDB(bd_dd_info2);

            BD_DD_INFO bd_dd_info3 = new BD_DD_INFO();
            bd_dd_info3.setDATAINFO("电话");
            bd_dd_info3.setDATANUM("3");
            bd_dd_info3.setID("DM04-15_3");
            bd_dd_info3.setPARENTID("DM04-15");
            bd_dd_info3.setSORT("3");
            bd_dd_info3.setNBPHSC("Y");
            bd_dd_info3.setPrintNum("3");
            NovaApplication.fdbmanger.saveInInfoDB(bd_dd_info3);

        }
        List<BD_DD_INFO> bd_dd_infos = NovaApplication.fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
                "ID = 'DM04-04_2'");
        if (bd_dd_infos != null && bd_dd_infos.size() > 0) {
            BD_DD_INFO bd_dd_info = bd_dd_infos.get(0);
            if ("家庭".equals(bd_dd_info.getDATAINFO())) {
                bd_dd_info.setDATAINFO("家庭访视");
                NovaApplication.fdbmanger.updataInInfoDB(bd_dd_info, "ID = 'DM04-04_2'");
            }
        }
    }

    /**
     * 打开设置界面
     */
    public void openSettingDetail() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(intent);
    }

    private void initCSDB() {
        SBCL_DATA sb = new SBCL_DATA();// 设备测量
        NovaApplication.fdbmanger.save(sb);
        HD_PERSONAL_HEALTH_PHOTO photo = new HD_PERSONAL_HEALTH_PHOTO();// 照片
        NovaApplication.fdbmanger.save(photo);
    }

    /**
     * 初始化数据表格
     *
     * @author 王婷婷
     * @date 2017年7月26日 下午8:05:23
     */
    private void initDbData() {
        JTYSCustomerDoctorCont jtys_khqyb = new JTYSCustomerDoctorCont();// 家庭签约医生表
        NovaApplication.fdbmanger.save(jtys_khqyb);

        SPUtil.setRegisterImei(this, code);
        NovaApplication.setImei(code);
        SPUtil.setIsShiYong(this, true);
        SPUtil.setRegisterXZQ(this, AREA_CODE);
    }

    @Override
    public void findViews() {
        tv_version = (TextView) findViewById(R.id.tv_version);
        String versionName = GlobalConts.getVerName(SplashActivity.this);
        if (!TextUtils.isEmpty(versionName)) {
            tv_version.setText("V  " + versionName);
        } else {
            tv_version.setText("");
        }

    }

    @Override
    public void setListeners() {

    }

    class StartHandler implements Runnable {

        @Override
        public void run() {
//            jumpNextActivity();
            mContext.startActivity(new Intent(mContext, LoginActivity.class));
            mContext.finish();
        }

    }

    private void jumpNextActivity() {
        Intent intent = null;

        if (TextUtils.isEmpty(NovaApplication.getImei()) || TextUtils.isEmpty(NovaApplication.getXzqhNo())
                || SPUtil.getIsShiYong(SplashActivity.this)) {

            intent = new Intent(getApplication(), RegisterActivity.class);
        } else {
            List<BD_DD_AREA> areas = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
                    "GBCODE like'" + NovaApplication.getXzqhNo() + "%'");
            List<BD_ORGANIZE_INSTITUTION> institutions = NovaApplication.fdbmanger
                    .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "GBCODE like'" + NovaApplication.getXzqhNo() + "%'");

            List<BD_ORGANIZE_EMPLOYEE> employees = NovaApplication.fdbmanger.findAll(BD_ORGANIZE_EMPLOYEE.class,
                    "GBCODE ='" + NovaApplication.getXzqhNo() + "'");
            if (areas.size() == 0 || institutions.size() == 0 || employees.size() == 0) {
                intent = new Intent(getApplication(), HomeDataDownloadActivity.class);
            } else {
                intent = new Intent(getApplication(), ConfigActivity.class);
            }
        }
        if (intent != null) {
            startActivity(intent);
            SplashActivity.this.finish();
        }
    }

}
